import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

/**
 * @author hewei
 * @version 1.0
 * @description: TODO
 * @date 2022/11/1 20:42
 */

public class ZeroEvenOdd2 {

    private int n;
    private Semaphore semaphore;
    private Semaphore semaphore1;
    private Semaphore semaphore2;

    public ZeroEvenOdd2(int n) {
        this.n = n;
        // release相当于放一个许可进去，acquire相当于拿走一个许可，当没有许可时，就会阻塞
        semaphore = new Semaphore(1);
        semaphore1 = new Semaphore(0);
        semaphore2 = new Semaphore(0);
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            semaphore.acquire();
            printNumber.accept(0);
            if (i % 2 == 0) {
                semaphore1.release();
            } else {
                semaphore2.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            semaphore2.acquire();
            printNumber.accept(i);
            semaphore.release();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            semaphore1.acquire();
            printNumber.accept(i);
            semaphore.release();
        }
    }
}
